<template>
  <div class="app-container">
    <el-tabs v-model="activeTabName" @tab-click="handleTabClick">
    <el-tab-pane label="创建订单" name="first">
      <el-card shadow="hover">
        <div slot="header" class="clearfix">
          <i class="el-icon-plus"></i>
          <span> 创建订单</span>
        </div>
        <div class="text item">
        <el-form ref="form" :model="orderItemVo" :inline="true" label-width="68px">
          <!-- 创建订单 -->
          <el-form-item>
            <el-button
              type="primary"
              size="small"
              icon="el-icon-plus"
              :disabled="BtnDisabled"
              @click="handleEnterOrder"
            >新建订单</el-button>
          </el-form-item>
          <el-form-item label="商品编码" prop="clId">
            <el-input
              v-model="orderItemVo.clId"
              placeholder="请输入商品编码"
              size="small"
              clearable
              @keyup.enter.native="handleEnterclothes"
            />
          </el-form-item>
          <el-form-item label="服饰尺码" prop="clSize">
            <el-select v-model="orderItemVo.clSize" clearable placeholder="请选择">
              <el-option v-for="item in options" 
              :key="item.value" 
              :label="item.label" 
              :value="item.value" 
              @keyup.enter.native="handleEnterclothes">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              size="small"
              :disabled="BtnDisabled"
              @click="handleEnterclothes"
              icon="el-icon-edit-outline"
            >录入</el-button>
          </el-form-item>
          <!--  -->
          <el-form-item>
              <el-button type="danger" size="small" round icon="el-icon-delete" @click="handleCancelOrder"> 取消下单 </el-button>
              <el-button type="success"  size="small" round icon="el-icon-check" :disabled="BtnDisabled" @click="openPayDialog()"> 确认下单 </el-button>
          </el-form-item>

        </el-form>
        </div>
      </el-card>
      
    
    </el-tab-pane>

    <el-tab-pane label="订单查询" name="second">
      <el-card shadow="hover">
        <div slot="header" class="clearfix">
          <i class="el-icon-search"></i>
          <span> 查询订单</span>
          </div>
        <div class="text item">

        <el-form inline="true" :model="queryParams" ref="queryForm">
          <el-form-item label="订单编号" prop="orderId">
            <el-input
              v-model="queryParams.orderId"
              placeholder="请输入订单编号"
              size="small"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        <!-- 查询订单 -->
          <el-form-item>
            <el-button
              type="primary"
              size="small"
              icon="el-icon-search"
              @click="handleQuery"
            >查询订单</el-button>
          </el-form-item>
        <!--  -->
        </el-form>
        </div>
      </el-card>

    </el-tab-pane>
    </el-tabs>

    <el-row :gutter="10" class="mb8">
      <el-col :span="24">
      <el-collapse v-model="activeCollapseName">
        <el-collapse-item title="订单信息" name="one">
          <el-form :model="orderItemVo" ref="orderInfoForm" label-width="100px">
            <el-col :span="8">
              <el-card>
                <el-col :span="64">
                  <el-form-item label="订单流水号:">{{ orderInfoForm.orderId }}</el-form-item>
                </el-col>
              </el-card>
            </el-col>
            <el-col :span="16">
              <el-card>
                <el-col :span="6">
                  <el-form-item label="订单总售价:">
                    <div class="card-panel-num1">{{ orderInfoForm.orderTotalAmount }}</div>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="订单应付款:">
                    <div class="card-panel-num1">{{ orderInfoForm.orderTotalRealpayment }}</div>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="订单优惠:">
                    <div class="card-panel-num1">{{ orderInfoForm.promotionsDiscount }}</div>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="订单购买总数:">
                    <div class="card-panel-num2">{{ orderInfoForm.orderTotalQuantity }}</div>
                  </el-form-item>
                </el-col>
              </el-card>
            </el-col>
          </el-form>
        </el-collapse-item>
      </el-collapse>
      </el-col>
    </el-row>
    <el-row :gutter="10">
      <el-col :span="24" :xs="24">
        <div slot="header" class="clearfix" style="line-height: 30px">
          <span><i class="el-icon-s-unfold"></i> 订单列表商品</span><el-divider direction="vertical"></el-divider>
        </div>
          <el-table v-loading="loading" :data="orderItemList">
            <el-table-column label="商品编号" align="center" prop="clId" />
            <el-table-column label="服饰名称" align="center" prop="clName" />
            <el-table-column label="服饰类别" align="center" prop="clCategoryName" />
            <el-table-column label="服饰尺码" align="center" prop="clSize" />
            <el-table-column label="服饰售价" align="center" prop="clSalePrice" />
            <el-table-column label="单件优惠" align="center" prop="discount" />
            <el-table-column label="单件应付款" align="center" prop="payment" />
            <el-table-column label="商品数量" align="center" prop="quantity" />
          </el-table>     
      </el-col>
    </el-row>

    <el-dialog title="支付" :visible.sync="open" width="20%" :before-close="closePayDialog">
      <!-- 支付方式选择，按钮显示 -->
        <div class="pay-dialog-body" v-if="payBtn == true">
            <p>请选择支付方式：</p>
            <el-button type="primary" size="small" @click="handlePayWxQRcode">微信支付</el-button>
            <el-button type="primary" size="small" @click="handlePayAliQRcode">支付宝支付</el-button>
        </div>
      <!-- 支付方式选择完成，按钮消失 -->
        <div v-if="payBtn == false">
            <div>
                使用 
                <span v-if="payForWx == true" class="pay-for-method-1">微信</span>
                <span v-if="payForAli == true" class="pay-for-method-2">支付宝</span> 
                扫一扫二维码进行支付
            </div>
            <!-- 微信支付二维码 -->
            <iframe 
                v-if="payForWx == true"
                :srcdoc="payWeChatQRcode" 
                frameborder="no" 
                border="0"
                marginwidth="10" 
                marginheight="10" 
                scrolling="no" 
                width="220" 
                height="220"
                style="overflow: hidden;">
            </iframe>
<!--             <div id="qrcodeImg"></div>
 -->
             <!-- 支付宝支付二维码 -->
            <iframe 
                v-if="payForAli == true"
                :srcdoc="payAliQRcode" 
                frameborder="no" 
                border="0"
                marginwidth="10" 
                marginheight="10" 
                scrolling="no" 
                width="220" 
                height="220"
                style="overflow: hidden;">
            </iframe>
            <div>注：若二维码过期失效，请刷新页面重新进入支付！</div>
        </div>
        <span slot="footer">
            <el-button @click="closePayDialog" size="small">返回</el-button>
        </span>
    </el-dialog>
  </div>
</template>

<script>
import { getOrder, listOrderItem, enterOrder, enterGsClothes, enterPayment, cancelOrder} from '@/api/orderItem'
export default {
  name: 'OrderItem',
  data() {
    return {
      open: false,      // 是否打开支付弹窗
      payBtn: true,    // 是否显示方式选择按钮
      payInfoRow: {},    // 该条订单数据
      payForWx: false,    // 是否微信支付
      payForAli: false,    // 是否支付宝支付
      payWay: '',       //支付方式
      timer: '',    // 定时器
      payWeChatQRcode: '',    // 微信codeURL
      payAliQRcode: '',    // 支付宝codeURL

      options: [{
          value: 'S',
          label: 'S'
        }, {
          value: 'M',
          label: 'M'
        }, {
          value: 'L',
          label: 'L'
        }],

      // 下单按钮状态
      BtnDisabled: false,

      // 输入：录入商品编码vo
      orderItemVo: {
        clId:undefined,
        clSize: undefined,
      },
      // 输入：查询参数
      queryParams: {
        orderId: undefined,
      },

      // 输入/输出：订单及业务信息
      orderInfoForm: {
        orderId: undefined,
        orderTotalAmount: undefined,
        orderTotalPayment: undefined,
        promotionsDiscount: undefined,
        orderTotalQuantity: undefined,
      },
      // 输出：订单列表商品/待下单商品列表
      orderList:[],
      orderItemList: [],
    
/*       orderInfoForm: {
        order: {
          orderItemList: [
          {
            id: undefined,
            orderId: undefined,
            orderItemId: undefined,
            orderdSaleTime: undefined,
            clId: undefined,
            gsClothes: {
              id: undefined,
              clId: undefined,
              clName: undefined,
              clCategoryId: undefined,
              clMaterial: undefined,
              clSize: undefined,
              clInventory: undefined,
              clSalePrice: undefined,
              clCost: undefined,
            },
            gsCategory: {
              id: undefined,
              clCategoryId: undefined,
              clCcategoryName: undefined,
            },
            orderItemAmount: undefined,
            promotionsDiscount: undefined,
            orderItemRealpayment: undefined,
            orderItemQuantity: undefined,
          },
          ],
        orderTotalAmount: undefined,
        orderTotalPayment: undefined,
        promotionsDiscount: undefined,
        orderTotalQuantity: undefined,
        },
        
      }, */
      // 激活的tab名称
      activeTabName: 'first',
      
      // 展开的折叠面板
      activeCollapseName: 'one'
    }
  },
  
  created() {

  },
  methods: {
    
    getOrderList() {
      this.loading = true;
      //订单业务信息
      getOrder(this.orderInfoForm.orderId).then((response) => {
        this.orderInfoForm = response.data;
        this.loading = false;
      });
    },
    /** 查询订单（明细）列表 */
    getOrderItemList() {
      this.loading = true;
      //订单明细列表
      listOrderItem(this.orderInfoForm.orderId).then((response) => {
        this.orderItemList = response.data;
        this.loading = false;
      });
    },

    /** 表单重置 */
    resetorderInfoForm() {
      this.orderInfoForm = {
        orderId: undefined,
        orderTotalAmount: undefined,
        orderTotalPayment: undefined,
        promotionsDiscount: undefined,
        orderTotalQuantity: undefined,
      };
    },
    retsetorderItemVo(){
      this.orderItemVo = {
        clId: undefined,
        clSize: undefined,
      };
    },

    /** 创建订单信息 */
    handleEnterOrder() {
      this.clearAllData();
      this.resetorderInfoForm();
      enterOrder().then((response) => {
        this.orderInfoForm.orderId = response.data
        /* this.enterOrderItemList = response.data.order.orderItemList */
      })
    },
    /** 录入商品 */
    handleEnterclothes() {
      enterGsClothes(this.orderInfoForm.orderId, this.orderItemVo.clId, this.orderItemVo.clSize).then((response) => {
        const flag = response.data
        if (flag) {
          this.$message.success('已录入');
          this.getOrderList();
          this.getOrderItemList();
        } else {
          this.$message.error('操作失败')
        }
      })
      this.retsetorderItemVo()
    },
    
    /** 搜索按钮操作 */
    handleQuery() {/* 
      this.geOrderItemList(); */
      //订单业务信息
      getOrder(this.queryParams.orderId).then((response) => {
        if(response.data){
          this.orderInfoForm = response.data;
          this.loading = false;
          this.$message.success("查询成功");
        }else{
          this.resetorderInfoForm();
          this.$message.error("请重新输入订单编号");
        }

      });
      //订单明细列表
      listOrderItem(this.queryParams.orderId).then((response) => {
        this.orderItemList = response.data;
        this.loading = false;
      });
      
    },
    /** 切换tab */
    handleTabClick(tab, event) {
    },
    /** 确认下单 */
/*     confirmSubmit() {
      this.clearAllData();
      this.$message.success('下单成功');
    }, */
/*     qrcode(url) {  // 前端根据 URL 生成微信支付二维码
      return new QRCode('qrcodeImg', {
          width: 100,
          height: 100,
          text: url,
          colorDark: '#000',
          colorLight: '#fff'
      });
    },
 */    openPayDialog(){  // 打开支付窗口
      this.open = true;
      this.payBtn = true;    // 显示支付方式选择按钮
      this.payForWx = false;
      this.payForAli = false;
/*       this.payInfo = this.orderInfoForm.orderTotalRealpayment;    // 获取该条订单数据
 */    },
    closePayDialog(){  // 关闭支付窗口
      this.open = false;
      this.payBtn = true;
      this.payForWx = false;
      this.payForAli = false;
      clearInterval(this.timer);    // 清除定时器
    },
    handlePayWxQRcode(){  // 获取微信支付二维码
      this.payBtn = false;
      this.payForWx = true;
      this.timer = setInterval(() => {    // 通过定时器每间隔一会去请求查询微信支付状态（具体参数根据项目需要而定）
        this.handleQueryWxPayStatus();
      }, 3000);
/*       url = 'weixin://wxpay/bizpayurl?appid=wx2421b1c4370ec43b';
      this.qrcode(url);    // 例如：res.data.url 的值为 "weixin://wxpay/bizpayurl?pr=......"，根据这个值生成相对应的微信支付二维码
 */     
/*       this.timer = setInterval(() => {    // 通过定时器每间隔一会去请求查询微信支付状态（具体参数根据项目需要而定）
        this.handleQueryWxPayStatus();
      }, 500);
 */      /* this.payBtn = false;
      this.$api.order.getWxPayCode({    // 这里根据不同的后端接口去修改
        totalFee: row.totalAmount * 100,
        outTradeNo: row.orderSn,
      }).then(res => {
          this.qrcode(res.data.url);    // 例如：res.data.url 的值为 "weixin://wxpay/bizpayurl?pr=......"，根据这个值生成相对应的微信支付二维码
          this.payForWx = true;
          this.timer = setInterval(() => {    // 通过定时器每间隔一会去请求查询微信支付状态（具体参数根据项目需要而定）
            this.handleQueryWxPayStatus(row, res.data.outTradeNo);
          }, 1000);
        }) */
    },
    handleQueryWxPayStatus(){  // 查询微信支付状态
/*       this.$message({ type: 'success', message: '支付成功！' });
 */      this.payWay = '微信';
      enterPayment(this.orderInfoForm.orderId, this.payWay).then((response) => {
        const flag = response.data
        if (!flag) {
          this.$message.success('支付成功！');
          this.getOrderList();
          this.getOrderItemList();
        } else {
          this.$message.error('支付失败')
        }
      })
      this.closePayDialog();    // 关闭支付弹窗
      this.clearAllData();
      /* this.$api.order.queryWxPayStatus({    // 这里根据不同的后端接口去修改
        totalFee: row.totalAmount * 100,
        outTradeNo: sn,
      }).then(res => {
        if(res.data.paySuccess == true){    // 当查询到支付成功时
          this.$message({ type: 'success', message: '支付成功！' });
          this.closePayDialog();    // 关闭支付弹窗
          // 这里可以加个刷新订单列表的接口请求函数的调用
        }
      }) */
    },
    handlePayAliQRcode(){  // 获取支付宝支付二维码
      this.payBtn = false;
      this.payForAli = true;
      this.timer = setInterval(() => {    // 通过定时器每间隔一会去请求查询支付宝支付状态（具体参数根据项目需要而定）
        this.handleQueryAliPayStatus();
      }, 3000);
      /* this.payBtn = false;
      this.$api.order.getAliPayCode({    // 这里根据不同的后端接口去修改
        totalAmount: row.totalAmount,
        outTradeNo: row.orderSn,
      }).then(res => {
        this.payAliQRcode = res.data.url;    // 支付宝的二维码生成用 iframe 标签
        this.payForAli = true;
        this.timer = setInterval(() => {    // 通过定时器每间隔一会去请求查询支付宝支付状态（具体参数根据项目需要而定）
          this.handleQueryAliPayStatus(row, res.data.outTradeNo);
        }, 1000);
      }); */
    },
    handleQueryAliPayStatus(/* row ,sn */){  // 查询支付宝支付状态
/*       this.$message({ type: 'success', message: '支付成功！' });
 */      this.payWay = '支付宝';
      enterPayment(this.orderInfoForm.orderId, this.payWay).then((response) => {
        const flag = response.data
        if (!flag) {
          this.$message.success('支付成功！');
          this.getOrderList();
          this.getOrderItemList();
        } else {
          this.$message.error('支付失败')
        }
      })
      this.closePayDialog();    // 关闭支付弹窗
      this.clearAllData();
    /*   this.$api.order.queryAliPayStatus({    // 这里根据不同的后端接口去修改
        totalAmount: row.totalAmount,
        outTradeNo: sn,
      }).then(res => {
        if(res.data.paySuccess == true){    // 当查询到支付成功时
          this.$message({ type: 'success', message: '支付成功！' });
          this.closePayDialog();    // 关闭支付弹窗
            // 这里可以加个刷新订单列表的接口请求函数的调用
        }
      }); */
    },
    handleCancelOrder(){
      cancelOrder(this.orderInfoForm.orderId);
      this.retsetorderItemVo();
      this.resetorderInfoForm();
      this.getOrderList();
      this.getOrderItemList();
    },
    /** 清除数据 */
    clearAllData() {
      Object.assign(this.$data, this.$options.data.call(this))
    }
  },

  beforeDestroy(){
    clearInterval(this.timer);
  }

}
</script>

<style lang="scss" scoped>
  .card-panel-num1 {
    font-size: 30px;
    color: #40c9c6;
  }
  .card-panel-num2 {
    font-size: 40px;
    color: #eb0f0f;
  }
  .mb8 {
    margin-bottom: 8px;
  }

  .pay-dialog-body p{
    margin-bottom: 10px;
  }
  #qrcodeImg{
    margin: 10px;
  }
  .pay-for-method-1{
    font-weight: bold;
    color: #67c23a;
  }
  .pay-for-method-2{
    font-weight: bold;
    color: #409eff;
  }
</style>




